<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\SystemMessage;

/**
 * 系统消息接口
 */
class Message extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 系统消息列表
     * 
     * @ApiTitle    (系统消息列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="per_page", type="integer", required=false, description="每页数量", default=10)
     * @ApiParams   (name="type", type="string", required=false, description="消息类型:goods=商品订单,travel=文旅订单,service=服务订单,VIP=vip订单")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": 100,
          "per_page": 10,
          "current_page": 1,
          "last_page": 10,
          "data": [{
            "id": 1,
            "type": "goods",
            "type_text": "商品订单",
            "title": "订单状态更新",
            "content": "您的订单xxx已发货",
            "order_no": "202401010001",
            "is_read": 0,
            "createtime": 1672502400,
            "createtime_text": "2024-01-01 12:00:00"
          }]
        }
      })
     */
    public function index()
    {
        $page = $this->request->get('page', 1);
        $per_page = $this->request->get('per_page', 10);
        $type = $this->request->get('type', '');
        
        $where = ['user_id' => $this->auth->id];
        if ($type) {
            $where['type'] = $type;
        }
        
        $total = SystemMessage::where($where)->count();
        $list = SystemMessage::where($where)
            ->page($page, $per_page)
            ->order('id DESC')
            ->select();
            
        $this->success('', [
            'total' => $total,
            'per_page' => $per_page,
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'data' => $list
        ]);
    }
    
    /**
     * 标记消息已读
     * 
     * @ApiTitle    (标记消息已读)
     * @ApiMethod   (POST)
     * @ApiParams   (name="ids", type="string", required=true, description="消息ID，多个用逗号分隔")
     */
    public function read()
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $ids = explode(',', $ids);
        SystemMessage::where('user_id', $this->auth->id)
            ->whereIn('id', $ids)
            ->update(['is_read' => 1]);
            
        $this->success('操作成功');
    }

    public function getImUserMessageCount(){
        $user_id = 'guoxue_user_'.$this->auth->id;
        $Common = new Common();
        $count = $Common->getImUserMessageCount($user_id);
        $this->success('获取成功', ['count' => $count]);
    }
}